package com.xiguaji.tiktok.task.aweme;

import cn.hutool.core.io.resource.ResourceUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
@Slf4j
public class ESAwemeService {
    private final String AWEME_INDEX = "aweme_index_";

    @Autowired
    RestHighLevelClient highLevelClient;

    public void createAwemeIndex(){
        String curAwemeIndex = AWEME_INDEX+LocalDateTime.now().plusMonths(1).format(DateTimeFormatter.ofPattern("yyyyMM"));
        GetIndexRequest getIndexRequest = new GetIndexRequest(curAwemeIndex);
        //getIndexRequest.humanReadable(true);
        try{
            val exists = highLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);

            if(!exists){
                String mappingJson = ResourceUtil.readUtf8Str("aweme.json");
                CreateIndexRequest createIndexRequest = new CreateIndexRequest(curAwemeIndex);
                createIndexRequest.settings(Settings.builder()
                        .put("index.number_of_shards",8)
                        .put("index.number_of_replicas",1));

                createIndexRequest.mapping(mappingJson, XContentType.JSON);
                highLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
                log.info(">>>>>>{}索引创建成功",curAwemeIndex);
                return;
            }

            log.info(">>>>>>{}索引已存在，无法创建",curAwemeIndex);
        }catch (Exception e){
            log.error("create index: {} error",curAwemeIndex,e);
        }
    }

    public void deleteAwemeIndex(){
        String curAwemeIndex = AWEME_INDEX+LocalDateTime.now().minusMonths(2).format(DateTimeFormatter.ofPattern("yyyyMM"));
        GetIndexRequest getIndexRequest = new GetIndexRequest(curAwemeIndex);

        try{
            val exists = highLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);

            if(exists){
                DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(curAwemeIndex);
                highLevelClient.indices().delete (deleteIndexRequest,RequestOptions.DEFAULT);
                log.info(">>>>>>{}索引删除成功",curAwemeIndex);
                return;
            }
            log.info(">>>>>>{}索引不存在，无法删除",curAwemeIndex);
        }catch (Exception e){
            log.error("delete index: {} error",curAwemeIndex,e);
        }
    }
}
